﻿namespace Blaze.Framework.LuaExtensions.FileLoaders
{
    using FileSystems;

    public class FromFileSystem
    {
        public FromFileSystem(FileSystem fileSystem)
        {
            mFileSystem = fileSystem;
        }

        public byte[] ReadFile(ref string filePath)
        {
            filePath = filePath.Replace(".", "/");
            var ret = readFileInternal($"{filePath}.lua", ref filePath);
            if (ret == null)
                ret = readFileInternal($"{filePath}/init.lua", ref filePath);
            return ret;
        }

        private byte[] readFileInternal(string resPath, ref string filePath)
        {
            var stream = mFileSystem.Open(resPath);
            if (stream == null)
                return null;
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            filePath = $"fs://{resPath}";
            return bytes;
        }

        private readonly FileSystem mFileSystem;
    }
}